package cn.tedu.micro.demo.order.service.impl;

import cn.tedu.micro.demo.common.protocol.JsonResult;
import cn.tedu.micro.demo.common.vo.GunInfoVO;
import cn.tedu.micro.demo.order.clients.DeviceClient;
import cn.tedu.micro.demo.order.dao.repository.OrderRepository;
import cn.tedu.micro.demo.order.pojo.po.OrderInfoPO;
import cn.tedu.micro.demo.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private DeviceClient deviceClient;
    @Override
    public String createOrder(Integer userId, Integer gunId) {
        //日志格式
        log.info("开始处理创建订单业务,参数:userId={},gunId={}",userId,gunId);
        //1 利用枪id查询枪状态
        Integer status=checkGunStatus(gunId);
        //判断
        if (status!=1){
            log.error("枪状态异常,无法下单");
            throw new RuntimeException("枪状态异常,无法下单");
        }else{
            log.info("开始处理创建订单业务,参数:userId={},gunId={}",userId,gunId);
            //2.生成订单编号
            String billId= UUID.randomUUID().toString().replace("-","");
            //3.封装po
            OrderInfoPO po=new OrderInfoPO();
            po.setBillId(billId);
            po.setUserId(userId);
            po.setGunId(gunId);
            //4.保存到数据库
            orderRepository.saveOrder( po);
            log.info("订单创建成功,订单编号:{}",billId);
            return billId;
        }
    }

    private Integer checkGunStatus(Integer gunId) {
        //1.调用feingClient接口
        JsonResult<GunInfoVO> result = deviceClient.checkGunStatus(gunId);
        //2.读取判断调用结果 如果code!=0说明调用失败 抛出异常逻辑额流程结束
        if (result.getCode()!=0){
            log.error("调用设备服务失败,异常信息:{}",result.getMessage());
            throw new RuntimeException("调用设备服务失败");
        }else{
            GunInfoVO vo = result.getData();
            return vo.getStatus();
        }
    }
}
